//
//  BanBu_SnapImageView.m
// Halfarea
//
//  Created by Wang Xj on 14-2-11.
//
//

#import "BanBu_SnapImageView.h"

@implementation BanBu_SnapImageView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _snapImageView = [[UIImageView alloc]initWithFrame:frame];
        [self addSubview:self.snapImageView];
        [_snapImageView release];
        
        _timeImage = [[UIImageView alloc]initWithFrame:CGRectMake(200, 30, 54+16, 54+16)];
        _timeImage.image = [UIImage imageNamed:@"timer_button@2x.png"];
        _timeImage.backgroundColor = [UIColor clearColor];
        
        _timeLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];
        _timeLabel.font = [UIFont systemFontOfSize:14];
        _timeLabel.textColor = [UIColor blackColor];
        _timeLabel.textAlignment = UITextAlignmentCenter;
        _timeLabel.backgroundColor = [UIColor clearColor];
        _timeLabel.hidden = YES;

        _timeLabel.center = CGPointMake(35, 36);
        
        [_timeImage addSubview:_timeLabel];
        [self addSubview:_timeImage];
        [_timeImage release];
        
        self.backgroundColor = [UIColor clearColor];
        
    }
    return self;
}
-(void)dealloc
{
    [_snapImageView release],_snapImageView = nil;
    [_timeImage release], _timeImage = nil;
    [_timeLabel release],_timeLabel = nil;
//    [super dealloc];
}

//倒计时
-(void)countdownCounter:(NSInteger)effectiveTime
{
    if (!_timeLabel.hidden)
    {
        return;
    }

    _timeLabel.text = [NSString stringWithFormat:@"%d",effectiveTime];
    __block int timeout = effectiveTime; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    _timeLabel.hidden = NO;
    
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0)
        { //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_release(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                _timeLabel.textColor = [UIColor blackColor];
                _timeLabel.hidden = YES;
                [self removeFromSuperview];
            });
        }
        else
        {
            NSString *strTime = [NSString stringWithFormat:@"%ds",timeout];
            NSInteger time = timeout;
            dispatch_async(dispatch_get_main_queue(), ^{
                if (time<=3)
                {
                    _timeLabel.textColor = [UIColor redColor];
                }
                //设置界面的按钮显示 根据自己需求设置
                self.timeLabel.text = strTime;
            });
            timeout--;
        }  
    });  
    dispatch_resume(_timer);
}



@end
